package com.lc.hongtai.activity;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lc.hongtai.MyApplication;
import com.lc.hongtai.R;
import com.lc.hongtai.adapter.BorrowingTestAdapter;
import com.lc.hongtai.conn.JsonAccessToken;
import com.lc.hongtai.conn.JsonBorrowingCancel;
import com.lc.hongtai.conn.JsonBorrowout;
import com.lc.hongtai.toast.LovelyToast;
import com.lc.hongtai.view.SimpleDividerItemDecoration;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;


public class BorrowManageDetailActivity extends BaseActivity implements View.OnClickListener {
    private List<String> stringList = new ArrayList<>();
    //发标中的借款
    private String show_type = "borrowing";
    public int nowPage = 1;
    private boolean canLoadMore = true;
    private PtrFrameLayout store_house_ptr_frame;
    private PtrClassicDefaultHeader header;
    private RecyclerView rv01;


    public static List<JsonBorrowout.Info.ListContent> list = new ArrayList<>();

    private PopupWindow popLeft;
    private View layoutLeft;
    private ListView menulistLeft;

    @Bind(R.id.tv_01)
    TextView tv_01;

    @Bind(R.id.invest_title_ll)
    LinearLayout invest_title_ll;

    private RecyclerView.Adapter mAdapter;
    //BorrowingTestAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    public int totalPages = 1;
    public int pageSize = 0;
    public int totalRows = 0;


    private List<String> entityLists = new ArrayList<>();
    private List<String> mDatas;

    @Bind(R.id.pop_layout)
    LinearLayout pop_layout;
    String item_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invest_manage_detail3);
        ButterKnife.bind(this);
        initView();

        stringList.clear();
        stringList.add("成功转让债权");
        stringList.add("回收中债权");
        stringList.add("进行中债权");
        stringList.add("可转债权");

        stringList.add("已撤销债权");
        stringList.add("已购买债权");

        initData();

         mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);

        //mAdapter = new BorrowingAdapter(BorrowManageDetailActivity.this, list, this);
        rv01.setLayoutManager(mLayoutManager);
        rv01.setAdapter(mAdapter);

        getAccessToken(true, nowPage);
        initRefreshListener();
    }

    public void initView() {


        header = new PtrClassicDefaultHeader(this);
        this.store_house_ptr_frame = (PtrFrameLayout) findViewById(R.id.store_house_ptr_frame);
        this.rv01 = (RecyclerView) findViewById(R.id.rv_01);
        rv01.setHasFixedSize(true);

        invest_title_ll.setOnClickListener(this);
        header = new PtrClassicDefaultHeader(this);
        store_house_ptr_frame.setHeaderView(header);
        mLayoutManager = new LinearLayoutManager(this);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.line_divider3);
        rv01.addItemDecoration(new SimpleDividerItemDecoration(this, drawable, 2));

    }

    private void getAccessToken(final boolean isShow, final int page) {
        new JsonAccessToken("user/borrow_in", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initData(info.access_token, isShow, page);
                    } else {
                        //  UtilToast.show(InvestManageDetailActivity.this, "安全验证失败！");
                        LovelyToast.makeText(BorrowManageDetailActivity.this, "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        canLoadMore = true;
                        if (!isShow) {
                            store_house_ptr_frame.refreshComplete();
                        }
                    }
                }


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //   UtilToast.show(InvestManageDetailActivity.this, "安全验证失败！");
                LovelyToast.makeText(BorrowManageDetailActivity.this, "安全验证失败！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                canLoadMore = true;
                if (!isShow) {
                    store_house_ptr_frame.refreshComplete();
                }
            }
        }).execute(this, isShow);

    }

    private void initData(String access_token, final boolean isShow, final int page) {
//uid
        new JsonBorrowout(access_token, MyApplication.myPreferences.readUid(), "", "", show_type, page,

                new AsyCallBack<JsonBorrowout.Info>() {

                    @Override
                    public void onStart(int type) throws Exception {
                        super.onStart(type);
                    }

                    @Override
                    public void onSuccess(String toast, int type, JsonBorrowout.Info info) throws Exception {
                       /* LovelyToast.makeText(BorrowManageDetailActivity.this, "请求成功！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);*/
                        if (info != null) {
                            list.clear();
                            list.addAll(info.list);


                            nowPage = info.page.nowPage;
                            totalPages = info.page.totalPages;
                            pageSize = info.page.pageSize;
                            totalRows = info.page.totalRows;
                            totalPages = info.page.totalPages;
                            pageSize = info.page.pageSize;
                            totalRows = info.page.totalRows;
                            if (list.isEmpty()) {
                                // ToastUtils.show(InvestManageDetailActivity.this, "无记录！");
                                LovelyToast.makeText(BorrowManageDetailActivity.this, "无记录！", 0, LovelyToast
                                        .SUCCESS, LovelyToast.SCALE);
                            }
                        }


                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                        //   UtilToast.show(InvestManageDetailActivity.this, JsonTendout.TOAST);
                        LovelyToast.makeText(BorrowManageDetailActivity.this, "安全验证失败", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        store_house_ptr_frame.refreshComplete();
                    }

                    @Override
                    public void onEnd(String toast, int type) throws Exception {
                        if (!isShow) {
                            store_house_ptr_frame.refreshComplete();
                        }
                        canLoadMore = true;
                        mAdapter.notifyDataSetChanged();
                    }

                }).execute(BorrowManageDetailActivity.this, isShow);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                Integer position = (Integer) view.getTag();
                JsonBorrowout.Info.ListContent listContent = list.get(position);
                item_id = listContent.id;


                // Toast.makeText(BorrowManageDetailActivity.this, listContent.id, Toast.LENGTH_SHORT).show();
                getAccessToken();
                break;


            case R.id.invest_title_ll:

                getPopLayout();
                break;


        }
    }


    public void getPopLayout() {

        if (popLeft != null && popLeft.isShowing()) {
            popLeft.dismiss();
        } else {

            layoutLeft = LayoutInflater.from(context).inflate(R.layout.pop_menulist1, null);
            menulistLeft = (ListView) layoutLeft
                    .findViewById(R.id.menulist);
            menulistLeft.setAdapter(new ArrayAdapter<String>(BorrowManageDetailActivity.this, R.layout.pop_list_item, stringList));

            menulistLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // textCity.setText(list.get(position));
                    tv_01.setText(stringList.get(position));
                    //   typeid=typelist.get(position).id;
                    // popupWindow.dismiss();


                    if (!list.isEmpty()) {
                        list.clear();
                    }

                    nowPage = 1;
                    switch (position) {
                        case 0:
                            //成功转让债权
                            show_type = "borrowing";
                           mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);
                            //成功转让的债权

                         //   mAdapter = new BorrowingAdapter(BorrowManageDetailActivity.this, list, BorrowManageDetailActivity.this);

                            rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;
                        case 1:
                            //回收中债权
                            show_type = "borrowpaying";
                             mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);
                            //回收中的债权
                         //   mAdapter = new BorrowpayingAdapter(BorrowManageDetailActivity.this, list);
                            rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;

                        case 2:

                            //  进行中债权
                            show_type = "borrowbreak";
                              mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);
                           // mAdapter = new OutDataAdapter(BorrowManageDetailActivity.this, list);
                            rv01.setAdapter(mAdapter);
                            // rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;
                        case 3:
//                           可转债权
                            show_type = "borrowfail";
                            mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);
                         //   mAdapter = new BorrowingLiubiaoAdapter(BorrowManageDetailActivity.this, list);
                            rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;

                        case 4:
                            //已撤销债权
                            show_type = "borrowfail1";
                          //  mAdapter = new FirstFailAdapter(BorrowManageDetailActivity.this, list);
                            mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);
                            rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;


                        case 5:

//                            已购买债权
                            show_type = "borrowfail2";
                            mAdapter = new BorrowingTestAdapter(BorrowManageDetailActivity.this, mDatas);
                          //  mAdapter = new SecondFailAdapter(BorrowManageDetailActivity.this, list);
                            //    mAdapter = new SecondFainAdapter(BorrowManageDetailActivity.this, mDatas);
                            rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;


                    }


                    popLeft.dismiss();
                }
            });
            popLeft = new PopupWindow(layoutLeft, pop_layout.getWidth(),
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.colorWhite));
            popLeft.setBackgroundDrawable(cd);
            popLeft.setAnimationStyle(R.style.PopupAnimation);
            popLeft.update();
            popLeft.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            popLeft.setTouchable(true); // 设置popupwindow可点击
            popLeft.setOutsideTouchable(true); // 设置popupwindow外部可点击
            popLeft.setFocusable(true); // 获取焦点

            popLeft.showAsDropDown(pop_layout, 0, 0);
            popLeft.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 如果点击了popupwindow的外部，popupwindow也会消失
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        popLeft.dismiss();
                        return true;
                    }
                    return false;
                }
            });

        }


    }

    private void initRefreshListener() {
        rv01.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                if (dy > 0 && canLoadMore && lastVisibleItemPosition + 1 == mAdapter.getItemCount()) {
                    canLoadMore = false;
                    if (nowPage < totalPages) {
                        getAccessToken(true, nowPage + 1);


                    } else {
                        //UtilToast.show(InvestManageDetailActivity.this, "当前页已是最后一页");
                    }
                }
            }
        });

        store_house_ptr_frame.setPtrHandler(new PtrHandler() {


            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibleItemPosition();
                return firstVisibleItemPosition == 0 || mDatas.size() == 0;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mDatas.clear();
                nowPage = 1;
                getAccessToken(false, nowPage);


            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }

    /*  private void initRefreshListener() {
        rv01.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                if (dy > 0 && canLoadMore && lastVisibleItemPosition + 1 == mAdapter.getItemCount()) {
                    canLoadMore = false;
                    if (nowPage < totalPages) {
                        getAccessToken(true, nowPage + 1);
                    } else {
                        //UtilToast.show(InvestManageDetailActivity.this, "当前页已是最后一页");
                    }
                }
            }
        });

        store_house_ptr_frame.setPtrHandler(new PtrHandler() {


            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
              *//*  int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibleItemPosition();
                return firstVisibleItemPosition == 0 || list.size() == 0;*//*
                int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibleItemPosition();
                return (firstVisibleItemPosition == 0 || list.size() == 0);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                list.clear();
                nowPage = 1;
                getAccessToken(false, nowPage);
            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
             header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }
*/
    protected void initData() {
        mDatas = new ArrayList<String>();
        for (int i = 'A'; i < 'z'; i++) {
            mDatas.add("" + (char) i);
        }
    }


    public void getAccessToken() {
        new JsonAccessToken("user/borrow_in_cancel", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                BorringCancel(info.access_token);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //   UtilToast.show(InvestManageDetailActivity.this, "安全验证失败！");
                LovelyToast.makeText(BorrowManageDetailActivity.this, "安全验证失败！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                canLoadMore = true;

            }
        }).execute(this);
    }


    public void BorringCancel(String access_token) {

        new JsonBorrowingCancel(access_token, MyApplication.myPreferences.readUid(), item_id, new AsyCallBack<JsonBorrowingCancel.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonBorrowingCancel.Info info) throws Exception {

                nowPage = 1;
                getAccessToken(true, nowPage);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                LovelyToast.makeText(BorrowManageDetailActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }

        ).execute(this, true);

    }
}
